#include"ipAddressPort.h"
#include"tcpServer.h"
#include"threadPool.h"
#include"reactor.h"
#include"ser.h"
#include"public.h"
#include"logger.h"



#include<unistd.h>
#include<sys/wait.h>
#include<fcntl.h>
#include<string.h>
Ser::Ser(std::string ip,size_t port,size_t numOfThreads)
  :ser_( TcpServer(IpAddressPort(ip,port)))
  ,pool_( ThreadPool(numOfThreads))
  ,reactor_( Reactor())
{
  reactor_.AddEventAndHander(ser_.GetLfd(),EV_READ | EV_PERSIST,Ser::ListenEventsCallback,this);
  reactor_.Loop();
}
 std::shared_ptr<Ser> Ser::GetInstance(std::string ip,size_t port,size_t numOfThreads)
 {
    
   if(!Ser::serInstance_)
   {
      std::unique_lock<std::mutex> pmutex(mutex_);
   }
   if(!Ser::serInstance_)
   {
     Ser::serInstance_ = std::shared_ptr<Ser>(new Ser(ip,port,numOfThreads));
   }
    return serInstance_;
 }
 Reactor & Ser::GetReactor()
 {
   return reactor_;
 }
 const TcpServer & Ser::Getser()const
 {
   return ser_;
 }

 void Ser::ListenEventsCallback(int fd,short events,void * arg)
{
  Ser *ser = static_cast<Ser *>(arg);
  
   if(EV_READ | events)
   {
     int cfd =ser->Getser().Accept();
     if(-1 == cfd)
     {
        LOG_ERROR<< "Accept failed!";
     }
     write(ser->pool_.GetSubThreadSocketPairFirst(),(char *)&cfd,4);
   }
}
 std::shared_ptr<Ser>Ser:: serInstance_ = nullptr;
 std::mutex Ser::mutex_;

int main()
{
  std::shared_ptr<Ser> Ser= Ser::GetInstance("127.0.0.1",8001,3);
  return 0;
}